package common.util;

import common.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 不需要用户登录（即不需要token）即可访问的url
 * 不会绕开spring security验证，相当于进入filter后再放行
 *
 * @author 米泽鹏
 */
public class PublicUrlAntPatternUtil {

	private static final List<String> ANT_PATTERNS = new ArrayList<>();
	private static final List<AntPathRequestMatcher> ANT_PATH_REQUEST_MATCHERS = new ArrayList<>();

	static {
		// 测试用
		// ANT_PATTERNS.add("/system/test/**");
		// ANT_PATTERNS.add("/game/test/**");
		// ANT_PATTERNS.add("/gateway/test-sharding/**");
		// ANT_PATTERNS.add("/system/test-sharding/**");
		// 静态资源
		ANT_PATTERNS.add("/static/**");
		ANT_PATTERNS.add("/webjars/**");
		ANT_PATTERNS.add("/**/*.css");
		ANT_PATTERNS.add("/**/*.js");
		ANT_PATTERNS.add("/**/*.png");
		ANT_PATTERNS.add("/**/*.gif");
		ANT_PATTERNS.add("/**/*.ftl");
		ANT_PATTERNS.add("/**/*.ttf");
		ANT_PATTERNS.add("/**/*.html");
		ANT_PATTERNS.add("/**/*.ico");
		// knife4j
		ANT_PATTERNS.add("/swagger-resources/**");
		ANT_PATTERNS.add("/**/v2/api-docs");
		// 其他
		ANT_PATTERNS.add("/favicon.ico");
		ANT_PATTERNS.add("/jrebel/**");
		ANT_PATTERNS.add("/agent/features");
		// 项目相关
		ANT_PATTERNS.add("/error");
		ANT_PATTERNS.add(SecurityConstants.LOGIN_PROCESSING_URL);
		ANT_PATTERNS.add(SpecialUrlUtil.REGISTER);
		ANT_PATTERNS.add("/system/modify-password/**");
		ANT_PATTERNS.add("/system/forget-password/**");
		ANT_PATTERNS.add("/system/user-email/**");
		ANT_PATTERNS.add("/system/oss/**");
		for (String antPattern : ANT_PATTERNS) {
			ANT_PATH_REQUEST_MATCHERS.add(new AntPathRequestMatcher(antPattern));
		}
	}

	private PublicUrlAntPatternUtil() {
		throw new AssertionError("不可实例化");
	}

	public static List<String> getAllPatterns() {
		return ANT_PATTERNS;
	}

	public static List<AntPathRequestMatcher> getAllMatchers() {
		return ANT_PATH_REQUEST_MATCHERS;
	}

	public static boolean isPublicUrl(HttpServletRequest request) {
		for (AntPathRequestMatcher matcher : ANT_PATH_REQUEST_MATCHERS) {
			if (matcher.matches(request)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isPublicUrl(String url) {
		for (AntPathRequestMatcher matcher : ANT_PATH_REQUEST_MATCHERS) {
			if (matcher.matches(url)) {
				return true;
			}
		}
		return false;
	}

}
